const { Document } = require('camo')
const battleAIs = require('../battle/ai')
const Move = require('../battle/move')

const tinygradient = require('tinygradient')
const tinycolor = require('tinycolor2')

const healthGradient = tinygradient(['#BA0020', '#ffbf00', '#77dd77'])
const colorDead = '#36454f'

// A Character refers to both a player and an enemy. The difference is in
// their `ai` that controls their actions (for players, this is DiscordAI).
class Character extends Document {
  constructor() {
    super()

    this.schema({
      discordID: {type: String, required: false},
      battleAI: {type: String, required: true, choices: Object.keys(battleAIs)},

      health: {type: Number, default: 5, min: 0},
      maxHealth: {type: Number, default: 5, min: 1},

      moves: [Move],
    })
  }

  // Rather than a string (this.battleAI), returns the class itself.
  get BattleAI() {
    return battleAIs[this.battleAI]
  }

  async modHealth(by, guild) {
    this.health += by

    if (this.health > this.maxHealth) this.health = this.maxHealth
    if (this.health < 0)              this.health = 0

    if (guild) await this.healthUpdate(guild)

    return this.healthState
  }

  async healthUpdate(guild) {
    await this.save()
    if (!this.discordID) return

    const member = guild.members.get(this.discordID)

    // Remove existing health role, if any
    const roleExisting = member.roles.find(role => role.name.endsWith(' health'))
    if (roleExisting) await roleExisting.delete()

    // Reuse/create a health role and grant it
    const roleName = `${this.health}/${this.maxHealth} health`
    const role = member.roles.find(role => role.name === roleName)
      || await guild.createRole({
        name: roleName,
        color: this.health === 0
          ? colorDead
          : tinycolor(healthGradient.rgbAt(this.health / this.maxHealth)).toHexString()
      })

    await member.addRole(role)
  }

  get healthState() {
    if (this.health === this.maxHealth) return 'healthy'
    else if (this.health === 1)         return 'peril'
    else if (this.health === 0)         return 'dead'
    else                                return 'injured'
  }

  getName(guild) {
    // FIXME: names for characters without accociated discord users (eg. ai enemies)
    return guild.members.get(this.discordID).displayName
  }
}

module.exports = Character
